<script setup lang="ts">
import type { PaginationProps } from '@arco-design/web-vue'

const props = withDefaults(
  defineProps<{
    title?: string
    loading?: boolean
    subtitle?: string
    indeterminate?: boolean
    breadcrumb?: string
    scroll?: boolean
    loadingText?: string
    showPagination?: boolean
    showBgWhite?: boolean
    class?: string
  }>(),
  {
    loading: false,
    showPagination: true,
    title: '',
    subtitle: '',
    scroll: true,
    showBgWhite: true,
  },
)
const emit = defineEmits<{
  (event: 'run'): void
}>()

const [DefineTemplate, ReuseTemplate] = createReusableTemplate()

const slots = useSlots()
const route = useRoute()

const checkedAll = defineModel<boolean | undefined>('checkedAll', {
  default: undefined,
})
const pagination = defineModel<
  | (PaginationProps & {
    current: number
    pageSize: number
  })
  | false
>('pagination', {
      default: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
    })
const tabs = ref<MetaTab[]>([])

const activeName = computed<string>(
  () => (route.params?.module as string) || '',
)

const router = useRouter()

function handleTabClick(key: string | number) {
  // @ts-ignore
  router.replace({ ...route, params: { ...route.params, module: key } })
}

watch(
  () => route.name,
  (val, oldVal) => {
    if (val !== oldVal) {
      tabs.value = route.meta.tabs || []
    }
  },
  { deep: true, immediate: true },
)
const breadcrumbs = computed(() => {
  const { meta } = route
  if (meta?.breadcrumbs) {
    return meta.breadcrumbs.concat({
      title: props?.breadcrumb || props?.title || route?.meta?.title || '',
      to: route.fullPath,
    })
  }
  return []
})

async function handlePaginationChange() {
  await nextTick()
  emit('run')
}
</script>

<template>
  <define-template>
    <a-breadcrumb
      v-if="breadcrumbs?.length"
      class="main-container__breadcrumb"
      :routes="breadcrumbs"
    >
      <template #item-render="{ route }">
        <router-link :to="route.to">
          {{ route.title }}
        </router-link>
      </template>
    </a-breadcrumb>
    <header
      v-if="title || $route?.meta?.title || $slots?.title"
      class="mb-6 mt-4 flex items-center"
    >
      <slot name="title">
        <div class="grid flex-1 space-y-1">
          <h1 class="m-0 text-xl font-bold">
            {{ title || $route?.meta?.title }}
          </h1>
          <p
            v-if="subtitle"
            class="text-xs/5 text-slate-500"
          >
            {{ subtitle }}
          </p>
        </div>
      </slot>
      <slot name="actions" />
    </header>
    <header
      v-if="$slots?.header"
      class="group mt-6 flex items-center space-x-3"
    >
      <slot name="header" />
      <span class="grow" />
      <a-button
        class="ml-auto shrink-0 text-color-1"
        type="outline"
        :disabled="loading"
        @click="emit('run')"
      >
        <template #icon>
          <i-icons-refresh :class="{ 'animate-spin': loading }" />
        </template>
      </a-button>
    </header>
    <div
      v-if="tabs?.length"
      class="mt-6"
    >
      <a-tabs
        :active-key="activeName"
        auto-switch
        hide-content
        @change="handleTabClick"
      >
        <a-tab-pane
          v-for="item in tabs"
          :key="item.key"
          :title="item.title"
        />
      </a-tabs>
    </div>
    <div class="mt-4 flex-1">
      <slot />
    </div>
    <div
      v-if="
        slots?.['footer-prefix'] || slots?.['footer-suffix'] || showPagination
      "
      class="flex items-center py-4"
    >
      <slot name="footer-prefix" />

      <slot name="footer-suffix">
        <a-pagination
          v-if="pagination && showPagination"
          v-bind="pagination"
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          class="main-container__pagination"
          show-page-size
          show-total
          :total="pagination.total || 0"
          :page-size-options="[10, 20, 30, 50, 100]"
          @change="handlePaginationChange"
          @page-size-change="handlePaginationChange"
        >
          <template
            v-if="slots?.total"
            #total="total"
          >
            <slot
              name="total"
              v-bind="total"
            />
          </template>
        </a-pagination>
      </slot>
    </div>
  </define-template>
  <a-spin
    class="size-full overflow-hidden rounded-xl"
    :loading="loading"
    :tip="loadingText"
    :class="{ 'resource-area': showBgWhite }"
  >
    <div
      class="main-container"
      :class="[{ 'p-6': !scroll }, props.class]"
    >
      <res-scrollbar
        v-if="scroll"
        :view-class="scroll ? 'p-6' : undefined"
      >
        <reuse-template />
      </res-scrollbar>
      <template v-else>
        <reuse-template />
      </template>
    </div>
  </a-spin>
</template>

<style scoped lang="less">
.main-container {
  @apply size-full relative;
  &__pagination {
    @apply w-full;
  }
}

.main-container__breadcrumb {
  :deep(.arco-breadcrumb-item-separator) {
    @apply leading-none;
  }

  :deep(.arco-breadcrumb-item) {
    @apply leading-none;

    a {
      @apply text-color-3 font-normal;
    }

    &:last-child {
      @apply pointer-events-none;

      a {
        @apply text-color-1;
      }
    }
  }
}
.arco-tabs {
  :deep(.arco-tabs-tab) {
    margin: 0 12px;
    &:first-child {
      margin-left: 0;
    }
    &:hover {
      .arco-tabs-tab-title {
        &::before {
          @apply bg-transparent;
        }
      }
    }
  }
}
</style>
